package org.tangdao.modules.file.utils;

import java.util.List;

import org.tangdao.common.collect.ListUtils;
import org.tangdao.common.lang.StringUtils;
import org.tangdao.common.utils.SpringUtils;
import org.tangdao.common.web.http.ServletUtils;
import org.tangdao.modules.file.model.domain.FileUpload;
import org.tangdao.modules.file.service.IFileUploadService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class FileUploadUtils {

	private static final class Static {
		private static IFileUploadService fileUploadService = SpringUtils.getBean(IFileUploadService.class);
	}

	public static IFileUploadService getFileUploadService() {
		return Static.fileUploadService;
	}

	/**
	 * 文件列表
	 * @param bizKey
	 * @param bizType
	 * @return
	 */
	public static List<FileUpload> findFileUpload(String bizKey, String bizType) {
		if (StringUtils.isNotBlank(bizKey) && StringUtils.isNotBlank(bizType)) {
			QueryWrapper<FileUpload> queryWrapper = new QueryWrapper<FileUpload>();
			queryWrapper.eq("biz_key", bizKey);
			queryWrapper.eq("biz_type", bizType);
			return getFileUploadService().select(queryWrapper);
		}
		return ListUtils.newArrayList();
	}

	//保存或者更新
	public static void saveFileUpload(String bizKey, String bizType) {
		if (!StringUtils.isBlank(bizKey) && !StringUtils.isBlank(bizType)) {
			String fileUploadId = ServletUtils.getParameter(bizType);
			if (StringUtils.isNotBlank(fileUploadId)) {
				String[] fileUploadIds = fileUploadId.split(",");
				for (String id : fileUploadIds) {
					FileUpload fileUpload = new FileUpload(id);
					fileUpload.setBizKey(bizKey);
					fileUpload.setBizType(bizType);
					getFileUploadService().saveOrUpdate(fileUpload);
				}
			}

			String fileUploadDelId = ServletUtils.getParameter(bizType + "__del");
			if (StringUtils.isNotBlank(fileUploadDelId)) {
				String[] fileUploadDelIds = fileUploadDelId.split(",");
				for (String id : fileUploadDelIds) {
					getFileUploadService().deleteById(id);
				}
			}
		}

	}
}
